package com.liangchao.screenrecorder;

import static java.lang.Thread.sleep;

import android.Manifest;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    //请求码
    private final static int REQUEST_CODE = 101;
    //权限请求码
    private final static int PERMISSION_REQUEST_CODE = 1101;

    //录屏工具
    MediaProjectionManager mediaProjectionManager;
    MediaProjection mediaProjection;

    //开始按钮，停止按钮
    Button bt_start,bt_end;
    //获取录屏范围参数
    DisplayMetrics metrics;
    //录屏服务
    ScreenRecordService screenRecordService;


    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mediaProjectionManager = (MediaProjectionManager) getApplicationContext().getSystemService(MEDIA_PROJECTION_SERVICE);
        screenRecordService = new ScreenRecordService();
        checkPermission();
        bt_start = (Button) findViewById(R.id.btn_start_recorder);
        bt_end = (Button) findViewById(R.id.btn_stop_recorder);
        bt_end.setClickable(false);

        bt_start.setOnClickListener(this::onClick);
        bt_end.setOnClickListener(this::onClick);
    }

    public void checkPermission(){
        if(
                (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!=
                PackageManager.PERMISSION_GRANTED) &&(ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.RECORD_AUDIO)!=PackageManager.PERMISSION_GRANTED)
        ){
            ActivityCompat.requestPermissions(this,new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO
            },PERMISSION_REQUEST_CODE);
        }
    }

    private void requestMediaProjection() {
        Intent captureIntent = mediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(captureIntent, REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == PERMISSION_REQUEST_CODE){
            if(grantResults.length>0 &&
                    (grantResults[0] != PackageManager.PERMISSION_GRANTED||grantResults[1]
                    != PackageManager.PERMISSION_GRANTED)){
                Toast.makeText(this, "请同意权限，否则功能异常", Toast.LENGTH_SHORT).show();
            } else if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
            && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "权限申请成功", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    //返回方法，获取返回的信息
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //首先判断请求码是否一致，结果是否ok
        if(requestCode == REQUEST_CODE && resultCode == RESULT_OK){

            mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
            screenRecordService.setMediaProjection(mediaProjection);
            //获取录屏屏幕范围参数
            metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            screenRecordService.setConfig(metrics.widthPixels,metrics.heightPixels,metrics.densityDpi);

            //录屏请求成功，使用工具MediaProjection录屏
            //从发送获得的数据和结果中获取该工具

//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                Intent service = new Intent(this,ScreenRecordService.class);
//                service.putExtra("code", resultCode);
//                service.putExtra("data", data);
//                startForegroundService(service);
//            }
            //参数传过去以后，如果在录制，提示
            if(screenRecordService != null && screenRecordService.isRunning()){
                Toast.makeText(MainActivity.this,"当前正在录屏，请不要重复点击哦！",Toast.LENGTH_SHORT).show();
            } else if(screenRecordService != null && !screenRecordService.isRunning()){
                //没有录制，就开始录制，弹出提示，返回主界面开始录制
                screenRecordService.startRecord();
            }

        }
    }


    @SuppressLint("ResourceAsColor")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_start_recorder:
                requestMediaProjection();

                bt_start.setClickable(false);
                bt_end.setClickable(true);

                break;
            case R.id.btn_stop_recorder:
                bt_end.setClickable(false);
                bt_start.setClickable(true);
                if(screenRecordService != null && !screenRecordService.isRunning()){
                    //没有在录屏，无法停止，弹出提示
                    Toast.makeText(MainActivity.this,"您还没有录屏，无法停止，请先开始录屏吧！",Toast.LENGTH_SHORT).show();
                }else if(screenRecordService != null && screenRecordService.isRunning()){
                    //正在录屏，点击停止，停止录屏
                    screenRecordService.stopRecord();
                }
                break;
            default:
                break;

        }
    }
}